package com.gemme.gemme.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.gemme.gemme.R;
import com.gemme.gemme.login.Constant;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.manager.DataPares;
import com.gemme.gemme.shequ.CommunityBean;
import com.gemme.gemme.shequ.Guangchang2Fragment;
import com.gemme.gemme.shequ.SqDetailBean;
import com.gemme.gemme.util.SPUtil;
import com.gemme.gemme.wode.PhotoMyActivity;
import com.luck.picture.lib.config.PictureMimeType;

import java.util.HashMap;
import java.util.List;

public class ChatDialog {
    BottomDialog dialog;
    private Context mContext;
    private String data;

    public void showDialog(Context mContext){
//new int[]{R.id.close}
        dialog = new BottomDialog(mContext, R.layout.chat_dialog,
                null);
        this.mContext = mContext;

        dialog.show();
        initView();
        dialog.setOnBottomItemClickListener(new BottomDialog.OnBottomItemClickListener() {
            @Override
            public void onBottomItemClick(BottomDialog dialog, View view) {
                //
            }
        });
    }

    LinearLayout ll_content;
    TextView et_search;
    private void initView() {
        View view = dialog.getView();
//        setEditTextView();

        ll_content = view.findViewById(R.id.ll_content);
//        setEditTextView();
        Window win = dialog.getWindow();

        et_search = view.findViewById(R.id.et_search);
/*        ll_content.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ChatInputDialog chatInputDialog = new ChatInputDialog();
                chatInputDialog.showDialog(mContext);
//                chatInputDialog.setListener();
                setEidtListener(chatInputDialog);
            }
        });*/

        view.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        et_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ChatInputDialog chatInputDialog = new ChatInputDialog();
                chatInputDialog.showDialog(mContext);
//                chatInputDialog.setListener();
//                setEidtListener(chatInputDialog,null);

                chatInputDialog.setOnStrChangeLIstener(new OnStrChangeLIstener() {
                    @Override
                    public void onChangeLIstener(String str) {
                        try {
                            SqDetailBean.DataBean data = sqDetailBean.getData();

                            //发布父评论
                            addCComments(sqDetailBean.getData().getId(),str,null,null,null);

                            chatInputDialog.dismiss();
                        }catch (Exception e){

                        }

                    }
                });
            }
        });
    }


    public void setContentId(String data) {
        this.data = data;
        getDataS();

    }
    List<ChatBean.DataBean.ListBeanX> listBeanXES;

    private void setData() {
        ll_content.removeAllViews();
        try {
            for (int i = 0; i < listBeanXES.size(); i++) {
                ChatBean.DataBean.ListBeanX listBeanX = listBeanXES.get(i);
                ChatView chatView = new ChatView(mContext);
                chatView.setData(listBeanX);
                ll_content.addView(chatView);
                setChatViewLIstener(chatView);
            }
        }catch (Exception e){

        }
    }

    private void setChatViewLIstener(ChatView chatView) {
        //回复主评论
        chatView.getTv_desc().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ChatInputDialog chatInputDialog = new ChatInputDialog();
                chatInputDialog.showDialog(mContext);
//                chatInputDialog.setListener();
                setEidtListener(chatInputDialog,chatView.getData());
            }
        });


        //回复子评论
        chatView.setOnChildClickLIstener(new ChatView.OnChildClickLIstener() {
            @Override
            public void onChildClickLIstener(Integer contentId, String toUserName, Integer toUserId, long pcommentsId) {
                ChatInputDialog chatInputDialog = new ChatInputDialog();
                chatInputDialog.showDialog(mContext);

                chatInputDialog.setOnStrChangeLIstener(new OnStrChangeLIstener() {
                    @Override
                    public void onChangeLIstener(String comments) {

                        //添加子评论
                        addCComments(contentId,comments,toUserName,toUserId,pcommentsId);
                        chatInputDialog.dismiss();
                    }
                });

            }
        });

        //点赞
        chatView.getIv_zan().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //
                ChatBean.DataBean.ListBeanX data = chatView.getData();
                int contentId = data.getContentId();
               /* chatView.setIsZan(!chatView.getIsZan());
                Integer praise = chatView.getIsZan() ? 0 : 1;*/
                int praise = chatView.getPraiseFlag();
                long id = data.getId();
                praiseComments(contentId,praise,id);
            }
        });

        //删除父评论
        chatView.getTv_desc().setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {

                ChatBean.DataBean.ListBeanX data = chatView.getData();
                int contentId = data.getContentId();
                long id = data.getId();
                String pcommentsId = null;
                boolean iscan = false;
                if(myUserId.equals(data.getUserId() + "")){
                    iscan = true;
                }
                if(!(isAllDelete || iscan)){//没有权限的话不弹窗
                    return false;
                }

                DeleteDialog deleteDialog = new DeleteDialog();
                deleteDialog.showDialog(mContext);
                deleteDialog.getTv_confirm().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        //删除父评论
                        delCComments(contentId,id,pcommentsId);
                        deleteDialog.dismisss();
                    }
                });

                return false;
            }
        });

        //删除子评论
        chatView.setOnLongClickLIstener(new ChatView.OnLongClickLIstener() {
            @Override
            public void OnLongClickLIstener(Integer contentId, Long id, Long pcommentsId,Integer userId) {

                boolean iscan = false;
                if(myUserId.equals(userId + "")){
                    iscan = true;
                }
                if(!(isAllDelete || iscan)){//没有权限的话不弹窗
                    return;
                }

                DeleteDialog deleteDialog = new DeleteDialog();
                deleteDialog.showDialog(mContext);
                deleteDialog.getTv_confirm().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        //删除子评论
                        delCComments(contentId,id,pcommentsId + "");
                        deleteDialog.dismisss();
                    }
                });

            }
        });
    }

    //删除评论
    private void delCComments(int contentId, long id, String pcommentsId) {
//        http://47.114.162.17:9999/community/appccomments/delCComments
//?contentId=47&id=1307592178397982720?pcommentsId=11111
        String url = DataManager.BaseUrl + "community/appccomments/delCComments?" +
                "contentId=" + contentId +
                "&pcommentsId=" + (pcommentsId == null ? "" : pcommentsId) +
                "&id=" + id
                ;
        HashMap<String, String> headHashMap = new HashMap<>();
        headHashMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
        DataManager.toServer2(mContext, url, DataManager.DELETE_TYPE, "", headHashMap, new DataManager.GeResponse(){

            @Override
            public void onResponse(String response) {

                try {
                    if(DataPares.isSucess(mContext,response)){

                    }

                    getDataS();
                }catch (Exception e){

                }
            }
        });

    }

    //点赞
    private void praiseComments(int contentId, Integer praise, long id) {
        try {

            String url = DataManager.BaseUrl + "community/appccomments/praiseComments?" +
                    "contentId=" + contentId +
                    "&praise=" + praise +
                    "&id=" + id
                    ;
            HashMap<String, String> headHashMap = new HashMap<>();
            headHashMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
            DataManager.toServer2(mContext, url, DataManager.GET_TYPE, "", headHashMap, new DataManager.GeResponse(){

                @Override
                public void onResponse(String response) {

                    try {
                        if(DataPares.isSucess(mContext,response)){

                        }

                        getDataS();
                    }catch (Exception e){

                    }
                }
            });
        }catch (Exception e){

        }
    }

    private void setEidtListener(ChatInputDialog chatInputDialog ,ChatBean.DataBean.ListBeanX beanX) {
        chatInputDialog.setOnStrChangeLIstener(new OnStrChangeLIstener() {
            @Override
            public void onChangeLIstener(String comments) {
                int contentId = beanX.getContentId();
                String userName = beanX.getUserName();
                int toUserId = beanX.getUserId();
                long pcommentsId = beanX.getId();
                //添加子评论
                addCComments(contentId,comments,userName,toUserId,pcommentsId);
                chatInputDialog.dismiss();
            }
        });
    }

    private void addCComments(Integer contentId, String comments, String userName,
                              Integer toUserId, Long pcommentsId) {
//        http://47.114.162.17:9999/community/appccomments/addCComments
        try {
            if(contentId < 0 || TextUtils.isEmpty(comments)){
                Toast.makeText(mContext, "请填写评论内容", Toast.LENGTH_SHORT).show();
            }

            String url = DataManager.BaseUrl + "community/appccomments/addCComments?" +
                    "contentId=" + contentId +
                    "&comments=" + comments +
                    "&userName=" + (userName == null ? "" : userName) +
                    "&toUserId=" + (toUserId == null ? "" : toUserId) +
                    "&pcommentsId=" + (pcommentsId == null ? "" : pcommentsId) + ""
                    ;
            HashMap<String, String> headHashMap = new HashMap<>();
            headHashMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
            DataManager.toServer2(mContext, url, DataManager.POST_TYPE, "", headHashMap, new DataManager.GeResponse(){

                @Override
                public void onResponse(String response) {

                    try {
                      if(DataPares.isSucess(mContext,response)){

                      }

                      getDataS();
                    }catch (Exception e){

                    }
                }
            });
        }catch (Exception e){

        }
    }
    SqDetailBean sqDetailBean = null;
    //判断是否可以最高删除权限--判断 社区详情页的userId和自己是否相等--社区发布者
    boolean isAllDelete = false;
    String myUserId;
    private void getDataS() {

        try {
            if(TextUtils.isEmpty(data))
                return;

            sqDetailBean = JSON.parseObject(data, SqDetailBean.class);
            //判断是否可以最高删除权限--判断 社区详情页的userId和自己是否相等--社区发布者
            int userId = sqDetailBean.getData().getUserId();
            myUserId = SPUtil.getDataForString(mContext, Constant.UserId, "");
            if(myUserId.equals(userId + "")){
                isAllDelete = true;
            }
        }catch (Exception e){

        }
        String url = DataManager.BaseUrl + "community/appccomments/find?current=1&size=100&childCurrent=1" +
                "&childsId=" + sqDetailBean.getData().getUserId() +
                "&contentId=" + sqDetailBean.getData().getId();
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
        DataManager.toServer2(mContext, url, DataManager.GET_TYPE, "", headMap, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try {
//                    ll_content
                    ChatBean chatBean = JSON.parseObject(response, ChatBean.class);

                    listBeanXES = chatBean.getData().getRecords();
                    setData();
                    System.out.println("");
                }catch (Exception e){

                }
            }
        });
    }









    private void setEditTextView() {


        View decorView = dialog.getWindow().getDecorView();
        View contentView = dialog.findViewById(Window.ID_ANDROID_CONTENT);// 此处的控件ID可以使用界面当中的指定的任意控件
//        View contentView = findViewById(R.id.rl_edit);// 此处的控件ID可以使用界面当中的指定的任意控件
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(getGlobalLayoutListener(decorView, contentView));

    }

    private ViewTreeObserver.OnGlobalLayoutListener getGlobalLayoutListener(final View decorView, final View contentView) {
        return new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                decorView.getWindowVisibleDisplayFrame(r);

                int height = decorView.getContext().getResources().getDisplayMetrics().heightPixels;
                int diff = height - r.bottom;

                if (diff != 0) {
                    if (contentView.getPaddingBottom() != diff) {
                        contentView.setPadding(0, 0, 0, diff);
                    }
                } else {
                    if (contentView.getPaddingBottom() != 0) {
                        contentView.setPadding(0, 0, 0, 0);
                    }
                }
            }
        };
    }



}
